﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using UIWindows.Attributes;
using UIWindows.Enums;
using UIWindows.Models;
using XingLucifer.IBase;

namespace UIWindows.Domains
{
    public class ObjectContainer
    {
        private static List<MenuViewModel> _view = new List<MenuViewModel>();
        private static List<TaskEventModel> _event = new List<TaskEventModel>();
        private static ConcurrentDictionary<string, object> _singletons = new ConcurrentDictionary<string, object>();
        public static bool Init { get => true; }

        static ObjectContainer()
        {
            try
            {
                var types = Assembly.GetExecutingAssembly().GetTypes();
                var parameter = types.Where(t => t.IsClass && t.Name.Contains("ViewModel")).ToList();
                var page = types.Where(t => t.IsClass && t.GetCustomAttribute<ViewFeatureAttribute>() != null).ToList();
                var singleton = types.Where(t => t.IsClass && t.GetCustomAttribute<SingletonAttribute>() != null).ToList();
                foreach (var item in singleton)
                {
                    try
                    {
                        _singletons.TryAdd(item.Name, Activator.CreateInstance(item));
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine();
                        if (ex.InnerException != null)
                        {
                            Console.WriteLine(ex.InnerException.ToString());
                            //RunLog($"内部异常：{ex.InnerException.ToString()}");
                        }
                    }
                  
                }
                foreach (var item in page)
                {
                    var vfa = item.GetCustomAttribute<ViewFeatureAttribute>();
                    var viewmodel = parameter.Where(t => t.Name == $"{item.Name}ViewModel").FirstOrDefault();
                    MenuViewModel viewModel = new MenuViewModel()
                    {
                        MenuName = vfa.MenuName,
                        MenuIcon = vfa.MenuIcon,
                        IsSingleton = vfa.IsSingleton,
                        Level = vfa.Level,
                        Index = vfa.Index,
                    };
                    if (viewModel.IsSingleton)
                    {
                        if (viewmodel == null) throw new Exception("请新建视图模型");
                        var ps = viewmodel.GetConstructors()[^1].GetParameters();
                        List<object> plist = new();
                        foreach (var p in ps)
                        {
                            plist.Add(_singletons.ContainsKey(p.ParameterType.Name) ? _singletons[p.ParameterType.Name] : null);
                        }
                        UserControl obj = Activator.CreateInstance(item) as System.Windows.Controls.UserControl;
                        obj.DataContext = Activator.CreateInstance(viewmodel, plist.ToArray());
                        viewModel.Context = obj;
                    }
                    else
                    {
                        viewModel.View = item;
                        viewModel.ViewModel = viewmodel;
                    }
                    _view.Add(viewModel);
                }
                _view.Sort((x, y) => x.CompareTo(y));
                var handlerTypes = types.Where(t => t.IsClass && t.GetCustomAttribute<TaskClassAttribute>() != null).ToList();
                foreach (var handlerType in handlerTypes)
                {
                    //try
                    //{
                    MethodInfo method = handlerType.GetMethod("Handle");
                    var pars = method.GetParameters();
                    Type entityType = pars[0].ParameterType;
                    var ps = handlerType.GetConstructors()[^1].GetParameters();
                    List<object> plist = new List<object>();
                    foreach (var p in ps)
                    {
                        plist.Add(_singletons.ContainsKey(p.ParameterType.Name) ? _singletons[p.ParameterType.Name] : null);
                    }
                    var handler = Activator.CreateInstance(handlerType, plist.ToArray());
                    _event.Add(new TaskEventModel()
                    {
                        TaskObject = handler,
                        TaskType = handlerType.GetCustomAttribute<TaskClassAttribute>().TaskType,
                        Handle = handler.GetType().GetMethod("Handle")
                    });
                    //}catch (Exception ex)
                    //{
                    //    Console.WriteLine(ex.ToString());
                    //}
                }


            }catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.ToString());
                    //RunLog($"内部异常：{ex.InnerException.ToString()}");
                }
            }
        }

        public static IList<MenuModel> GetMenuList(AuthorityTypes type) => _view.Where(x => (x.Level & type) != AuthorityTypes.无权限).Select(x => new MenuModel() { Name = x.MenuName, Icon = x.MenuIcon }).ToList();

        public static TaskEventModel ResolveEvent(XingLucifer.IBase.Enums.TaskTypes type)
        {
            var resu= _event.Where(x => x.TaskType == type).FirstOrDefault();
            return resu;
        }
            

        private static UserControl _viewCache;
        public static object ResolvePage(string key)
        {
            ShowLoad(x => x.UnLoad());
            var model = _view.FirstOrDefault(x => x.MenuName == key);
            if (model == null) return null;
            if (model.IsSingleton)
            {
                _viewCache = model.Context;
                ShowLoad(x => x.Load());
                return model.Context;
            }
            var ps = model.ViewModel.GetConstructors()[^1].GetParameters();
            List<object> plist = new List<object>();
            foreach (var p in ps)
            {
                plist.Add(_singletons.ContainsKey(p.ParameterType.Name) ? _singletons[p.ParameterType.Name] : null);
            }
            UserControl obj = Activator.CreateInstance(model.View) as System.Windows.Controls.UserControl;
            obj.DataContext = Activator.CreateInstance(model.ViewModel, plist.ToArray());
            _viewCache = obj;
            ShowLoad(x => x.Load());
            return obj;
        }

        private static void ShowLoad(Action<IViewStatus> action)
        {
            if (_viewCache?.DataContext is IViewStatus status)
            {
                action?.Invoke(status);
            }
        }

        public static T ResolveSingleton<T>() where T : new() => (T)(_singletons.ContainsKey(typeof(T).Name) ? _singletons[typeof(T).Name] : default);
    }
}
